import ala from '@/service/ala.js'
import {
  ElMessage,
  ElMessageBox
} from 'element-plus'

// 删除
export async function del(array, row) {
  if (row.parentId > 0) {
    ala.error('存在子分类不能删除')
  }
  ElMessageBox.confirm(
      `是否删除分类:${row.name}?`,
      '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    .then(async () => {
      var response = await ala.httpDelete('/relation/delete?id=' + row.id)
      if (response) {
        array = deleteArray(array, row)
        ala.toast('分类' + row.name + '删除成功')
        ElMessage({
          type: 'success',
          message: '分类' + row.name + '删除成功',
        })
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消成功',
      })
    })
  return array
}

function deleteArray(array, row) {
  array.forEach((one, index) => {
    if (row.fatherId === 0) {
      if (one.id === row.id) {
        array.splice(index, 1)
      }
    } else {
      if (one.children) {
        one.children.forEach((two, twoIndex) => {
          if (two.id === row.id) {
            one.children.splice(twoIndex, 1)
          } else {
            if (two.children) {
              two.children.forEach((three, threeIndex) => {
                if (three.id === row.id) {
                  two.children.splice(threeIndex, 1)
                }
              })
            }
          }
        })
      }
    }
  })
}
